#ifndef _JANNA_PLUGIN_INTERFACE_H_
#define _JANNA_PLUGIN_INTERFACE_H_

#include <QList>
#include <QMap>
#include <QObject>
#include <QString>
#include <QVariant>

#include "pubsub.h"

class JannaPluginInterface {
public:
    virtual ~JannaPluginInterface() = default;
    /**
     * @brief 插件名称
     * 
     * @return 插件名称 
     */
    virtual QString pluginName() = 0;
    /**
     * @brief 插件版本
     * 
     * @return  插件版本
     */
    virtual QString pluginVersion() = 0;
    /**
     * @brief 插件作者
     * 
     * @return 插件作者
     */
    virtual QString author() = 0;
    /**
     * @brief 消息响应
     * 
     * @param point 消息主题
     * @param param 消息参数
     * @return QMap<QString, QVariant> 响应消息后需要发布的消息参数
     */
    virtual QMap<QString, QVariant> handler(const JannaTopic& point, const QMap<QString, QVariant>& param) = 0;
    /**
     * @brief 初始化消息订阅
     * 
     * @param points 需要订阅的消息列表
     */
    void initPoints(QList<JannaTopic> points) {
        this->m_topic = points;
    }
    /**
     * @brief 过滤消息,只响应 metadata 中订阅的消息
     * 
     * @param topic 主题
     * @param param 参数
     */
    void pointHandlerInterceptor(const JannaTopic& topic, const QMap<QString, QVariant>& param) {
        if (this->m_topic.isEmpty()) {
            return;
        }
        foreach (auto t, this->m_topic) {
            if (t.source == topic.source && t.topic == topic.topic) {
                // 响应消息
                auto publishParam = handler(topic, param);
                // 发布消息
                if (!t.publish.isEmpty()) {
                    JannaTopic publishTopic;
                    publishTopic.source = author() + "." + pluginName();
                    publishTopic.topic  = t.publish;
                    Pubsub::getInstance()->publish(publishTopic, publishParam);
                }
                break;
            }
        }
    }

protected:
    /**
     * @brief 插件订阅的主题列表
     */
    QList<JannaTopic> m_topic;
};

QT_BEGIN_NAMESPACE

#define JannaPluginInterface_iid "com.laolang.janna.JannaPluginInterface"

Q_DECLARE_INTERFACE(JannaPluginInterface, JannaPluginInterface_iid)
QT_END_NAMESPACE

#endif
